package com.leon.security.service.impl;

import com.leon.security.pojo.Admin;
import com.leon.security.service.AdminService;
import com.leon.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired(required = false)
    private AdminService adminService;
    @Autowired(required = false)
    private RoleService roleService;
    
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Admin admin = adminService.login(userName);
        System.out.println(admin.getAid());
        if(admin == null){
            throw new UsernameNotFoundException("用户名错误");
        }
        //获取登录用户的角色列表
        List<String> rolesList = roleService.findRolesByAid(admin.getAid());
        //把数据库中的角色列表信息和security角色信息对象转换
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String role : rolesList) {
            authorityList.add(new SimpleGrantedAuthority(role));
        }
        //开启授权
        return new User(userName,admin.getApwd(),authorityList);
    }
}
